#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import pygtk
import gtk
import webbrowser
import gnome
import gnomeapplet
import gconf
import keybinder
import os
os.chdir('/home/anton/gnome-web-search-applet')
from engines import engine
from preferences import preferences_dialog

class search_applet:
    def __init__(self,applet,iid):
        self.applet=applet
        self.applet.set_applet_flags(gnomeapplet.EXPAND_MINOR | gnomeapplet.HAS_HANDLE)

        self.hbox = gtk.HBox()
        
        self.entry = gtk.Entry()
        self.entry.set_icon_from_stock(1,gtk.STOCK_FIND)
        
        self.create_right_menu()
        
        self.menu = gtk.Menu()
        self.menubar = gtk.MenuBar()
        self.item = gtk.ImageMenuItem("")
        
        self.engine_list = [engine("Wikipedia","http://en.wikipedia.org/w/index.php?search=",'favicon.ico'), \
            engine("Google","http://www.google.ru/search?q=",'favicon2.ico'), \
            engine("Yandex","http://yandex.ru/yandsearch?text=",'favicon3.ico')]
                    
        for nomad in self.engine_list:
            self.menu.append(nomad.create_item())
        i = 0      
        for nomad in self.engine_list:
            nomad.item.connect("activate", self.on_menu_select, i)
            i = i + 1
        
        self.selected_engine = 0
        self.current_qs = self.engine_list[self.selected_engine].query_string


        image = gtk.Image()
        image.set_from_file( self.engine_list[self.selected_engine].icon )
        self.item.set_image(image)
        self.item.set_submenu(self.menu)
        self.menubar.append(self.item)
        #Warning! Dirty hack ahead!
        self.menu_hack()

        
        #Keybinding and GConf related stuff
        self.client = gconf.client_get_default()
        self.client.add_dir('/desktop/gnome/keybindings/GWSA', gconf.CLIENT_PRELOAD_NONE)
        self.client.notify_add('/desktop/gnome/keybindings/GWSA/binding', self.on_keybinding_changed)
        if self.client.get_string('/desktop/gnome/keybindings/GWSA/binding') == None:
            self.keybinding = '<Alt>G'
            self.client.set_string('/desktop/gnome/keybindings/GWSA/binding',self.keybinding)
            self.client.set_string('/desktop/gnome/keybindings/GWSA/name','GWSA')
        else:
            self.keybind = self.client.get_string('/desktop/gnome/keybindings/GWSA/binding')
        keybinder.bind(self.keybind,self.on_hotkey)

        #Callback connections
        self.entry.connect("button_press_event", self.get_focus, self.applet)
        self.entry.connect("key_press_event", self.on_enter_key_press, self.applet)
        self.entry.connect("icon_press", self.on_entrys_icon_press, self.applet)        

        #Adding widgets to the applet
        self.hbox.pack_start(self.menubar)
        self.hbox.pack_start(self.entry)
        self.applet.add(self.hbox)
        self.applet.show_all()
        
    def open_browser(self):
        '''Open default browser with query URL'''
        if self.entry.get_text() != "":
            webbrowser.open(self.current_qs+self.entry.get_text())
    
    def get_focus(self, widget, event, applet):
        '''Give focus to applet'''
        self.applet.request_focus(event.time)

    def on_entrys_icon_press(self, widget, icon_pos, event, applet):
        '''Open browser on left button click on entry's icon'''
        if icon_pos == 1  and event.type == gtk.gdk.BUTTON_PRESS and event.button == 1:
            self.open_browser()
   
    def on_enter_key_press(self, widget, event, applet):
        '''Open browser when Enter key is pressed in applet's entry'''
        if event.keyval == 65293 or event.keyval == 65421:
            self.open_browser()
    
    def create_right_menu(self):
        '''Create applet's right click menu'''
        propxml="""
            <popup name="button3">
            <menuitem name="Item 1" verb="About" label="_About" pixtype="stock" pixname="gtk-about"/>
            </popup>"""
        verbs = [("About", self.show_about_dialog)]
        self.applet.setup_menu(propxml, verbs, None)
    
    def show_about_dialog(self, *arguments, **keywords):
        '''Show About dialog'''
        about_dialog = gtk.AboutDialog()
        about_dialog.set_name("GNOME Web Search Applet")
        about_dialog.set_version("0.1")
        about_dialog.set_logo(gtk.gdk.pixbuf_new_from_file("/home/anton/gnome-web-search-applet/logo.svg"))
        about_dialog.set_copyright("Copyright © 2010  Anton Melnikov")
        about_dialog.set_website("http://code.google.com/p/gnome-web-search-applet/")
        about_dialog.set_comments("A Web search applet for GNOME panel")
        about_dialog.set_license("AMLLE: Do whatever you want.")
        about_dialog.show()

    def on_hotkey(self):
        '''Give input focus to applet's entry when hotkey is pressed'''
        time = keybinder.get_current_event_time()
        self.applet.request_focus(time)
    
    def on_menu_select(self, widget, number):
        '''Change icon and current query string on menu item select'''
        self.selected_engine = number
        main_image = gtk.Image()
        main_image.set_from_file(self.engine_list[number].icon)
        self.item.set_image(main_image)
        self.current_qs = self.engine_list[number].query_string
        
    def on_keybinding_changed(self, client, connection_id, entry, data):
        '''Unbind old hotkey and bind new when GConf key changed'''
        keybinder.unbind(self.keybind)
        new_key = client.get_string('/desktop/gnome/keybindings/GWSA/binding') 
        keybinder.bind(new_key,self.on_hotkey)
        self.keybind = new_key
    
    def menu_hack(self):
        '''Need this to remove menubar's background image. If there is a better way - please let me know!'''
        gtk.rc_parse_string('''
        style "bookmarks-menubar-style"
        {
            GtkMenuBar::shadow-type = GTK_SHADOW_NONE
            GtkMenuBar::internal-padding = 0
            GtkMenuItem::horizontal-padding = 3
        }
        widget "*.bookmarks-menu" style "bookmarks-menubar-style"
        
        style "menu_color"
        {
        bg_pixmap[NORMAL] = "background.png"
        }
        widget_class "*Menu*" style "menu_color"
        ''')
        self.menubar.set_name("bookmarks-menu")
        self.item.set_name("bookmarks-menu")
    
    def load_preferences_from_gconf(self):
        pass
        
def factory(applet, iid):
    '''Main Bonobo function'''
    search_applet(applet,iid)
    #Хак для фона. Но его недостаточно!
    applet.set_background_widget(applet)
    return True;

#Block below is needed to run applet without putting it on panel    
if len(sys.argv) == 2 and sys.argv[1] == "run-in-window":
    main_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    main_window.set_title("GWSA")
    main_window.connect("destroy", gtk.main_quit) 
    app = gnomeapplet.Applet()
    search_applet(app, None)
    app.reparent(main_window)
    main_window.show_all()
    gtk.main()
    sys.exit()


if __name__ == '__main__':
    print "Starting factory"
    gnomeapplet.bonobo_factory("OAFIID:Gnome_Panel_Example_Factory", gnomeapplet.Applet.__gtype__, "Simple gnome applet example", "1.0", factory)
